package org.nobody.mallb2c.mallproduct.service.impl;

import org.apache.commons.lang.StringUtils;
import org.nobody.mallb2c.mallproduct.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.nobody.common.utils.PageUtils;
import org.nobody.common.utils.Query;

import org.nobody.mallb2c.mallproduct.dao.BrandDao;
import org.nobody.mallb2c.mallproduct.entity.BrandEntity;
import org.nobody.mallb2c.mallproduct.service.BrandService;
import org.springframework.transaction.annotation.Transactional;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

  @Autowired
  CategoryBrandRelationService categoryBrandRelationService;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    String key = (String) params.get("key");
    QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
    if(!StringUtils.isEmpty(key)){
      queryWrapper
        .eq("brand_id", key)
        .or()
        .like("name", key);
    }

    IPage<BrandEntity> page = this.page(
      new Query<BrandEntity>().getPage(params),
      queryWrapper
    );

    return new PageUtils(page);
  }

  @Transactional
  @Override
  public void updateDetail(BrandEntity brand) {
    //保证 cate-brand-relation表 冗余字段的数据一致
    this.updateById(brand);
    if (!StringUtils.isEmpty(brand.getName())) {
      categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());

      //todo 更新其它关联
    }
  }

  @Override
  public List<BrandEntity> getBrandsByIds(List<Long> brandIds) {
    return baseMapper.selectList(new QueryWrapper<BrandEntity>().in("brand_id", brandIds));
  }

}
